package com.benson.common.swagger.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.benson.common.swagger.service.ISwaggerAuthService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * Swagger 授权服务
 *
 * @author zhangby
 * @date 19/2/20 5:05 pm
 */
@Service
public class SwaggerAuthServiceImpl implements ISwaggerAuthService {

    /**
     * jwt 秘钥
     */
    @Value("${system.security_jwt_key:common_security}")
    private String jwtKey;

    @Override
    public boolean verifyToken(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        //解析token
        Claims claims = parseJWT(token);
        return ObjectUtil.isNotNull(claims);
    }


    /**
     * 解析token
     *
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
    public Claims parseJWT(String jsonWebToken, String base64Security) {
        String jwt = jsonWebToken.replace("Bearer ", "");
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(base64Security.getBytes())
                    .parseClaimsJws(jwt).getBody();
            return claims;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 解析token
     *
     * @param jsonWebToken
     * @return
     */
    public Claims parseJWT(String jsonWebToken) {
        return Optional.ofNullable(jsonWebToken)
                .filter(StrUtil::isNotBlank)
                .map(token -> parseJWT(token, jwtKey))
                .orElse(null);
    }
}
